package cn.gzsxt.controller;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.gzsxt.po.PageOut;
import cn.gzsxt.po.TaskDetail;
import cn.gzsxt.service.TaskService;
import cn.gzsxt.service.impl.TaskServiceImpl;
import cn.gzsxt.vo.MsgObj;

@WebServlet("/AddTask.oa")
public class AddTaskServlet extends HttpServlet {
	
	TaskService service = new TaskServiceImpl();
	PageOut page = new PageOut();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String cmd = req.getParameter("cmd");
		if (cmd.equals("taskList")){
			getTask(req,resp);
		} else if (cmd.equals("kW")){
			byKeyWord(req,resp);
		} else if (cmd.equals("pS")){
			byPageSize(req,resp);
		} else if (cmd.equals("pM")){
			pageMove(req,resp);
		} else if (cmd.equals("getPage")){
			getPage(req,resp);
		} else if (cmd.equals("add")){
			addTask(req,resp);
		} else if (cmd.equals("del")){
			delTask(req,resp);
		} else if (cmd.equals("upd")){
			updTask(req,resp);
		}
	}
	
	private void updTask(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		TaskDetail task = toTheClass(TaskDetail.class,req,resp);
		MsgObj msgObj = new MsgObj(0, "修改失败!!");
		int row = service.updTask(task);
		if (row == 1){
			msgObj = new MsgObj(1, "修改成功!!");
		}
		resp.getWriter().print(JSON.toJSONString(msgObj));
	}

	private void delTask(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String ids = req.getParameter("ids");
		MsgObj msgObj = new MsgObj(0, "删除失败!!");
		if (ids != null && ids.length() != 0) {
			int row = service.delTask(ids);
			if (row == 1){
				msgObj = new MsgObj(1, "删除成功!!");
			}
		}
		resp.getWriter().print(JSON.toJSONString(msgObj));
	}

	private void addTask(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		TaskDetail Task = toTheClass(TaskDetail.class,req,resp);
		MsgObj msgObj = new MsgObj(0, "添加失败!!");
		int row = service.addTask(Task);
		if (row == 1){
			msgObj = new MsgObj(1, "添加成功!!");
			page.setTotalCount(page.getTotalCount()+1);
		}
		resp.getWriter().print(JSON.toJSONString(msgObj));
	}
	
	private <T> T toTheClass(Class<T> clz, HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException{
		T obj = null;
		try {
			obj = clz.newInstance();
			BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class);
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor pd : pds){
				String name = pd.getName();
				System.out.println("name:"+name);
				String value = req.getParameter(name);
				System.out.println("value:"+value);
				Class<?> type = pd.getPropertyType();
				if (value != null){
					value = URLDecoder.decode(value,"UTF-8");
					Method setter = pd.getWriteMethod();
					if (type.equals(Double.class) || type.equals(double.class)){
						setter.invoke(obj, Double.valueOf(value));
					} else if (type.equals(int.class) || type.equals(Integer.class)){
						setter.invoke(obj, Integer.valueOf(value));
					} else if (type.equals(java.util.Date.class)){
						   setter.invoke(obj, new SimpleDateFormat().parse(value));
					} else if (type.equals(java.sql.Date.class)){
						setter.invoke(obj, strToDate(value));
					} else if (type.equals(String.class)){
						setter.invoke(obj, value);
					}
				}			
			}
			
		} catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return obj;		
		
	}
	
	public java.sql.Date strToDate(String strDate) { 
		String str = strDate; 
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 
		java.util.Date d = null; 
		try {
			d = format.parse(str); 
		} catch (Exception e) { 
			e.printStackTrace(); 
		} 
		java.sql.Date date = new java.sql.Date(d.getTime()); 
		return date; 
	}

	private void getPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//传送分页信息
		PrintWriter out = resp.getWriter();
		out.print(JSON.toJSONString(page));
		out.flush();
		out.close();
	}

	private void byPageSize(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String pageSize = req.getParameter("pageSize");
		if (pageSize != null && Integer.valueOf(pageSize) != null){
			page.setPageSize(Integer.valueOf(pageSize));
			showPage(page,req,resp);
		}		
	}

	private void byKeyWord(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String keyWord = req.getParameter("keyWord");
		if (keyWord != null){
			page.setKeyword(URLDecoder.decode(keyWord,"UTF-8"));
			showPage(page,req,resp);
		}		
	}

	private void pageMove(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String move = req.getParameter("move");
		if (move != null && Integer.valueOf(move) != null){
			Integer moves = Integer.valueOf(move);
			if (moves == 1024*1024){
				page.setCurrentPage(page.getTotalPage());
			} else if (moves == -1024*1024){
				page.setCurrentPage(1);
			} else {
				Integer currentPage = page.getCurrentPage();
				//重新设置当前页
				page.setCurrentPage(currentPage+moves);
			}			
			showPage(page,req,resp);
		}		
	}

	private void getTask(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		page = new PageOut();
		page.setPageSize(15);
		page.setKeyword("");
		page.setCurrentPage(1);
		showPage(page,req,resp);
	}
	
	private void showPage(PageOut page, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		PrintWriter out = resp.getWriter();
		List<TaskDetail> tasks = service.getSelectRows(page);
		page.setTotalCount(tasks.size());
		
		StringBuffer sb = new StringBuffer();		
		for (TaskDetail task : tasks){
			sb.append("<tr>");
			sb.append("<td><input id='task"+task.getTaskId()+"' name='ids' value='"+task.getTaskId()+"' type='checkbox'></td>");
			sb.append("<td>"+task.getTaskTitle()+"</td>");
			sb.append("<td>"+task.getClerk()+"</td>");
			sb.append("<td>"+task.getBeginTime()+" - "+task.getEndTime()+"</td>");
			sb.append("<td>"+transStatus(task.getStatus())+"</td>");
			sb.append("<td>"+transRushStatus(task.getRushStatus())+"</td>");
			sb.append("<td width='5%' class='mian_b_icon_01'><a class='label label-primary' onclick='checkDetail("+task.getTaskId()+")'>查看</a></td>");
			sb.append("<td width='5%' class='mian_b_icon_01'><a class='label label-warning' onclick='updateDetail("+task.getTaskId()+")'>修改</a></td>");
			sb.append("</tr>");
		}
		out.print(sb.toString());
		out.flush();
		out.close();
	}
	
	private String getRushColor(Integer rush) {
		switch (rush){
		case 1:
			return "text-warning";
		case 2:
			return "text-danger";
		default:
			return "text-navy";
		}
	}
	
	private String transRushStatus(Integer rush){
		switch (rush){
		case 1:
			return "紧急";
		case 2:
			return "重大";
		default:
			return "一般";
		}
	}
	
	private String transStatus(Integer status){
		switch (status){
		case 1:
			return "同意";
		case 2:
			return "拒绝";
		default:
			return "审核中";
		}
	}
}
